<template>
    <page-box>
        <template v-slot:header>
            <ask-breadcrumb>
                <template
                    v-for="(item, index) in $getBreadCrumbsName($route.path)"
                >
                    <ask-breadcrumb-item
                        :key="index"
                        v-if="item.path"
                        :to="'/' + item.path"
                        >{{ item.meta.title }}</ask-breadcrumb-item
                    >
                    <ask-breadcrumb-item :key="index" v-else>{{
                        item.meta.title
                    }}</ask-breadcrumb-item>
                </template>
                <ask-breadcrumb-item>查看数据</ask-breadcrumb-item>
            </ask-breadcrumb>
        </template>
        <div class="task-detail-header">
            <div class="title">
                <p class="name">{{ tableName }}</p>
                <p class="description">
                    {{ $route.query.description || "暂无描述" }}
                </p>
            </div>
            <div v-if="$route.query.status === '1'">
                <template v-if="tableName && tableName.includes('经办节点')">
                    <el-button @click="forward" class="blue">转交</el-button>
                    <el-button type="primary" @click="toFillIn" class="purple"
                        >提交</el-button
                    >
                </template>
                <template v-if="tableName && tableName.includes('审批节点')">
                    <el-button @click="toAcceptance(true)" class="blue"
                        >通过</el-button
                    >
                    <el-button
                        type="primary"
                        @click="toAcceptance(false)"
                        class="purple"
                        >不通过</el-button
                    >
                </template>
            </div>
        </div>
        <div class="task-detail-container">
            <div class="left">
                <!--                <el-form :inline="true" :model="searchForm">-->
                <!--                    <el-form-item label="填报单位">-->
                <!--                        <el-select v-model="searchForm.govId" multiple collapse-tags clearable filterable>-->
                <!--                            <el-option-->
                <!--                                v-for="item in departmentList"-->
                <!--                                :key="item.govId"-->
                <!--                                :label="item.govName"-->
                <!--                                :value="item.govId">-->
                <!--                            </el-option>-->
                <!--                        </el-select>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="填报人">-->
                <!--                        <el-select v-model="searchForm.userId" multiple collapse-tags clearable filterable>-->
                <!--                            <el-option-->
                <!--                                v-for="item in userList"-->
                <!--                                :key="item.userId"-->
                <!--                                :label="item.userName"-->
                <!--                                :value="item.userId">-->
                <!--                            </el-option>-->
                <!--                        </el-select>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="填报时间">-->
                <!--                        <el-date-picker-->
                <!--                            v-model="searchForm.time"-->
                <!--                            type="date"-->
                <!--                            value-format="yyyy-MM-dd HH:mm:ss"-->
                <!--                            placeholder="选择日期">-->
                <!--                        </el-date-picker>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item>-->
                <!--                        <el-button type="primary" @click="getTable">搜索</el-button>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item class="right-btn">-->
                <!--                        <el-button type="primary" @click="showExportSelect">导出数据</el-button>-->
                <!--                    </el-form-item>-->
                <!--                </el-form>-->
                <el-table
                    v-show="tableData.length"
                    :data="tableData"
                    class="pbb__table"
                    header-cell-class-name="pbb__table-thead"
                    cell-class-name="pbb__table-thead-cell"
                    row-class-name="pbb__table-thead-row"
                    row-key="id"
                    style="width: 100%"
                    @select="handleSelectionChange"
                >
                    <!--            <el-table-column-->
                    <!--                align="center"-->
                    <!--                type="selection"-->
                    <!--                :reserve-selection="true"-->
                    <!--                width="60">-->
                    <!--            </el-table-column>-->
                    <el-table-column
                        v-for="(item, index) in tableColumn"
                        :key="index"
                        :prop="item.prop"
                        :label="item.label"
                    >
                        <template slot-scope="scope">
                            <div v-if="item.valueType === 'upload-img'">
                                <div
                                    v-if="
                                        scope.row[item.prop] &&
                                            scope.row[item.prop].length
                                    "
                                >
                                    <img
                                        class="table-img"
                                        :src="scope.row[item.prop][0].url"
                                        alt=""
                                        @click="
                                            previewImg(scope.row[item.prop])
                                        "
                                    />
                                </div>
                            </div>
                            <div v-else-if="item.valueType === 'upload-video'">
                                <div
                                    v-if="
                                        scope.row[item.prop] &&
                                            scope.row[item.prop].length
                                    "
                                >
                                    <el-button
                                        type="primary"
                                        @click="
                                            previewVideo(scope.row[item.prop])
                                        "
                                        >点击播放</el-button
                                    >
                                </div>
                            </div>
                            <div v-else-if="item.valueType === 'upload-record'">
                                <div
                                    v-if="
                                        scope.row[item.prop] &&
                                            scope.row[item.prop].length
                                    "
                                >
                                    <el-button
                                        type="text"
                                        @click="
                                            previewVideo(
                                                scope.row[item.prop],
                                                'record'
                                            )
                                        "
                                        >播放</el-button
                                    >
                                </div>
                            </div>
                            <div v-else-if="item.valueType === 'upload-file'">
                                <div
                                    v-if="
                                        scope.row[item.prop] &&
                                            scope.row[item.prop].length
                                    "
                                >
                                    <el-link
                                        class="table-file"
                                        v-for="(it, idx) in scope.row[
                                            item.prop
                                        ]"
                                        :key="idx"
                                        type="primary"
                                        :href="it.url"
                                        target="_blank"
                                    >
                                        文件{{ idx + 1 }}
                                    </el-link>
                                </div>
                            </div>
                            <span
                                v-else
                                class="other-span"
                                :title="scope.row[item.prop]"
                                >{{ scope.row[item.prop] }}</span
                            >
                        </template>
                    </el-table-column>
                </el-table>
                <ask-empty-text
                    style="min-height: 400px;"
                    v-if="tableData.length === 0"
                >
                </ask-empty-text>
            </div>
            <!--            <div class="right">-->
            <!--                <process-log />-->
            <!--            </div>-->
        </div>
        <el-dialog title="填报" :visible.sync="showFillInBox" width="30%">
            <span>请扫码前往小程序进行填报</span>
            <img
                class="QR-code-img"
                src="~@/assets/mini-program-QR-code.jpg"
                alt="logo"
            />
        </el-dialog>
        <el-dialog
            title="导出"
            center
            width="30%"
            :close-on-click-modal="false"
            :visible.sync="dialogTableVisible"
            @close="closeExportSelect"
        >
            <el-select
                multiple
                collapse-tags
                clearable
                filterable
                v-model="exportSelection"
                @change="changeExportSelection"
            >
                <el-option
                    v-for="(item, index) in exportTableColumn"
                    :label="item.label"
                    :value="item.value"
                    :key="index"
                >
                </el-option>
            </el-select>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeExportSelect">取 消</el-button>
                <el-button type="primary" @click="exportData">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="备注" :visible.sync="showCommentDialog" width="30%">
            <div>{{ $route.query.comment || "暂无备注" }}</div>
        </el-dialog>
        <el-dialog
            :title="previewVideoItem.type ? '播放音频' : '预览视频'"
            :visible.sync="showVideoDialog"
            @close="closeVideoDialog"
            destroy-on-close
            width="40%"
        >
            <video
                ref="videoPlay"
                class="preview-video"
                style="max-width: 100%"
                controls
                name="media"
                v-if="!previewVideoItem.type"
            >
                <source :src="previewVideoItem.url" type="video/mp4" />
            </video>
            <audio
                ref="videoPlay"
                class="preview-video"
                v-else
                :src="previewVideoItem.url"
                controls="controls"
            ></audio>
        </el-dialog>
        <el-dialog
            title="不通过"
            :close-on-click-modal="false"
            :visible.sync="showRemarks"
            width="30%"
        >
            <el-form ref="form" :model="form">
                <el-input
                    type="textarea"
                    :autosize="{ minRows: 6, maxRows: 16 }"
                    placeholder="请输入未通过原因"
                    v-model="form.remark"
                >
                </el-input>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeShowRemarks">取消</el-button>
                <el-button type="primary" @click="toSubmit(false)"
                    >确认</el-button
                >
            </div>
        </el-dialog>
        <template v-slot:footer v-if="total > 0">
            <pagination
                :total="total"
                :page.sync="pageIndex"
                :limit.sync="pageSize"
                @pagination="getTable"
            />
        </template>
    </page-box>
</template>

<script lang="ts">
import { Component, Mixins } from "vue-property-decorator";
import FormMixin from "@/mixins/form.mixin.base.ts";
import { dialogPreviewImg } from "@/components/public/preview-img/index";
import ProcessLog from "./components/process-log/index.vue";
import { dialogForm } from "@/views/module-manage/src/components/send-range/form";
import { downLoadBase64File } from "@/utils";

@Component({
    name: "TaskNotPassNotAlive",
    components: {
        ProcessLog
    }
})
export default class TaskNotPassNotAlive extends Mixins(FormMixin) {
    form: any = {
        // 验收内容
        remark: ""
    };

    // 表格名称
    tableName: any = "";
    // 数据总数
    total = 0;
    // 每页数量
    pageSize = 10;
    // 当前页码
    pageIndex = 1;
    // 表格数据
    tableData = [];
    // 动态表头
    tableColumn: any = [];
    // 选中内容
    multipleSelection: any = [];
    // 显示导出选项
    dialogTableVisible = false;
    // 显示备注
    showCommentDialog = false;
    // 导出内容
    exportSelection: any = [];
    searchForm: any = {
        time: "",
        userId: [],
        govId: []
    };

    // 填报人列表
    userList: any = [];

    // 填报单位列表
    departmentList: any = [];
    oldChooseData: any = [];
    exportTableColumn: any = [];
    previewVideoUrl: any = "";
    previewType = "";
    previewVideoItem: any = {
        url: "",
        type: ""
    };

    showVideoDialog = false;
    // 显示填报小程序弹框
    showFillInBox = false;
    showRemarks = false;

    select: any = [];

    created() {
        this.initPage();
    }

    initPage() {
        this.getTable();
        this.tableName = this.$route.query.name;
    }

    // 查询表格
    async getTable() {
        // const { time, govId, userId } = this.searchForm;
        const res = await this.$server["task/getForm/info"]({
            data: {
                taskId: this.$route.query.id
            }
        });
        if (res.data.code === 200) {
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
            this.tableColumn = [
                {
                    prop: "executor",
                    label: "填报人姓名"
                }
            ];
            this.tableData.forEach((item: any, index: number) => {
                item.keyValue.forEach((it: any) => {
                    item[it.key] = [
                        "upload-img",
                        "upload-video",
                        "upload-file",
                        "upload-record"
                    ].includes(it.valueType)
                        ? this.formatUploadData(it.value)
                        : it.value;
                    if (index === 0) {
                        this.tableColumn.push({
                            prop: it.key,
                            label: it.key,
                            valueType: it.valueType
                        });
                    }
                });
            });
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 选中修改
    handleSelectionChange(val: any) {
        this.multipleSelection = val;
    }

    // 验收通过/不通过
    toAcceptance(val: boolean) {
        if (val) {
            this.toSubmit(true);
        } else {
            this.showRemarks = true;
        }
    }

    closeShowRemarks() {
        this.showRemarks = false;
        this.form.remark = "";
    }

    // 提交审核
    async toSubmit(val: boolean) {
        const res = await this.$server["task/audit"]({
            data: {
                taskId: this.$route.query.id,
                comment: this.form.remark,
                approvedStatus: val ? 1 : 2
            }
        });
        if (res.data.code === 200) {
            this.$message.success("操作成功!");
            this.closeShowRemarks();
            this.$router.go(-1);
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 转发
    async forward() {
        // await this.getForwardPerson();
        dialogForm({
            ids: this.select,
            disabledList: this.select,
            isSingle: true,
            sure: async(vm: any, model: any) => {
                vm.close();
                const userId = model.select.filter((item: any) => {
                    return this.select.indexOf(item) === -1;
                });
                if (!userId.length) return false;
                const res = await this.$server["task/forward"]({
                    data: {
                        taskId: this.$route.query.id,
                        userId: userId.join(",")
                    }
                });
                if (res.data.code === 200) {
                    this.$message.success("操作成功!");
                    this.$router.go(-1);
                } else {
                    this.$message.error(res.data.message || "接口请求错误!");
                }
            },
            close: () => {
                this.select = [];
            }
        });
    }

    // 获取转发人员
    async getForwardPerson() {
        const res = await this.$server["task/getForwardUser"]({
            data: {
                id: this.$route.query.formId
            }
        });
        if (res.data.code === 200) {
            this.select = res.data.data.map((item: any) => item.id);
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 填报
    toFillIn() {
        this.showFillInBox = true;
    }

    // 打开导出弹窗
    showExportSelect() {
        this.dialogTableVisible = true;
        this.exportTableColumn = this.tableColumn.map((item: any) => {
            return { ...item, label: item.label, value: item.label };
        });
        this.exportTableColumn.unshift({ label: "全部", value: "ALL_SELECT" });
    }

    // 关闭导出弹窗
    closeExportSelect() {
        this.dialogTableVisible = false;
        this.exportSelection = [];
        this.exportTableColumn = [];
        this.oldChooseData = [];
    }

    // 修改导出选项
    changeExportSelection(val: any) {
        // 1、点击全选，选中全部
        // 2、全选状态下，再次点击全选，取消全部选中
        // 3、全选状态下，取消了某个选中，就需要取消 全选 和 当前这个数据 的选中
        // 4、没有全选，但是勾选了除全选外的所有数据，就是全选了，就选中所有
        // 5、没有全选，但也没有勾选除全选外的所有数据，不做处理
        const allSelection = this.exportTableColumn.map(
            (item: any) => item.value
        );
        if (val.includes("ALL_SELECT")) {
            if (this.oldChooseData.includes("ALL_SELECT")) {
                if (val.length < allSelection.length) {
                    const index = val.indexOf("ALL_SELECT");
                    this.exportSelection.splice(index, 1);
                }
            } else {
                this.exportSelection = allSelection;
            }
        } else {
            if (this.oldChooseData.includes("ALL_SELECT")) {
                this.exportSelection = [];
            } else {
                if (val.length === allSelection.length - 1) {
                    this.exportSelection = allSelection;
                }
            }
        }
        this.oldChooseData = this.exportSelection;
    }

    // 导出数据
    async exportData() {
        const itemIds: any = [];
        this.exportSelection.forEach((item: any) => {
            if (item !== "ALL_SELECT") {
                itemIds.push(item);
            }
        });
        try {
            const res = await this.$server["task/exportData"]({
                data: {
                    id: this.$route.query.formId,
                    exportFields: itemIds.join(",")
                }
            });
            if (res.data && res.data.code === 200) {
                downLoadBase64File(this.tableName, res.data.data);
                this.closeExportSelect();
            } else {
                this.$message.error(res.data.message || "接口请求错误!");
            }
        } catch (error) {
            if (error.cancel) {
                return;
            }
            this.$message.error(error.message || "接口请求错误!");
            throw error;
        }
    }

    // 图片预览
    previewImg(urls: any) {
        const list = urls.map((item: any) => item.url);
        dialogPreviewImg({
            title: "预览图片",
            current: list
        });
    }

    // 视频预览
    previewVideo(file: any, type: any) {
        this.previewVideoItem = {
            url: file[0].url,
            type: type || ""
        };
        this.showVideoDialog = true;
        this.$nextTick(() => {
            (this.$refs.videoPlay as any).load();
        });
    }

    // 关闭视频预览
    closeVideoDialog() {
        this.showVideoDialog = false;
        this.previewVideoItem = {
            url: "",
            type: ""
        };
    }
}
</script>
<style scoped lang="scss">
.right-btn {
    float: right;
}

.task-detail-container {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    .left {
        width: 70%;
        height: 100%;

        .page-base-footer {
            min-width: unset !important;
        }
    }

    .right {
        width: calc(30% - 10px);
        height: 100%;
        background: #fff;
    }
}

.table-img {
    width: 120px;
    height: 80px;
    cursor: pointer;
    object-fit: contain;
}

.table-file {
    margin-right: 12px;
}

.acceptance-box {
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    margin-top: 10px;
    .label {
        margin-right: 20px;
        line-height: 36px;
    }
    .right {
        p {
            margin: 5px 0 10px 0;
        }
    }
}
.preview-video {
    display: block;
    margin: 0 auto;
}
</style>
